package com.fs.web;

import com.alibaba.fastjson.JSONObject;
import com.fs.pojo.User;
import com.fs.service.ReplyService;
import com.fs.service.UserService;
import com.fs.utils.BeanFactories;
import com.fs.utils.JsonData;
import com.fs.utils.ResponseJSONUtil;
import com.fs.utils.ValidateCodeUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UserServlet", value = "/user/*")
public class UserServlet extends HttpServlet {


    private UserService userService = BeanFactories.getBean(UserService.class);
    private HttpServletRequest req;
    private HttpServletResponse resp;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.req = request;
        this.resp = response;

        switch (req.getPathInfo()){
            case "/sendMsg":sendMsg();break;
            case "/loginByCode":loginByCode();break;
            case "/loginByPassword":loginByPassword();break;
            case "/register":register();break;
            case "/queryById":queryById();break;
            case "/queryStudentInClass": queryStudentInClass(); break;
            case "/queryStudentInClassSeacher": queryStudentInClassBySeacher(); break;
            case "/updateUser": updateUser();break;
        }


    }


    /**
     * 查询班级里面的学生通过学号或者姓名搜索
     */
    private void queryStudentInClassBySeacher() throws IOException {
        JSONObject data = JSONObject.parseObject(IOUtils.toString(req.getInputStream(), "utf-8"));
        String classId = data.getString("classId");
        String contition = data.getString("contition");
        List<User> users =userService.queryStudentByNameOrNumber(classId,contition);
        resp.getWriter().print(JSONObject.toJSONString(JsonData.buildSuccess(users)));
    }

    /**
     * 查询班级里面的全部学生业务
     */
    private void queryStudentInClass() throws IOException {
        String classId = req.getParameter("classId");
        List<User> users = userService.queryStudentInClass(classId);
        resp.getWriter().print(JSONObject.toJSONString(JsonData.buildSuccess(users)));
    }

    /**
     * 发送短信业务
     */
    private void sendMsg() {

        String phone = req.getParameter("phone");

        //随机生成4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4) + "";

        System.out.println("验证码：" + code);

        //发送短信
        if (StringUtils.isNotEmpty(phone)) {

            //这里先注释掉  因为发送短信要钱
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);

            //将验证码存入session 以备登录校验
            req.getSession().setAttribute("validateCode", code);
        }

    }

    /**
     * 验证码登录
     * @throws IOException
     */
    private void loginByCode() throws IOException {

        JSONObject data = JSONObject.parseObject(IOUtils.toString(req.getInputStream(), "utf-8"));

        String phone = data.getString("phone");

        String code = data.getString("code");   //验证码登录

        String validateCode = (String) req.getSession().getAttribute("validateCode"); //获取验证码


        if(!code.equals(validateCode))
            resp.getWriter().print(JSONObject.toJSONString(JsonData.buildError("短信验证码错误")));
        else{

            //查询手机号是否存在
            User user = userService.queryByPhone(phone);

            //不存在则注册
            if(user == null)
                resp.getWriter().print(JSONObject.toJSONString(JsonData.buildSuccess(null)));
            else{

                resp.getWriter().print(JSONObject.toJSONString(JsonData.buildSuccess(user.getId())));
            }

        }
    }


    /**
     * 用户密码登录
     */
    private void loginByPassword() throws IOException {

        JSONObject data = JSONObject.parseObject(IOUtils.toString(req.getInputStream(), "utf-8"));

        String phone = data.getString("phone");

        String password = data.getString("password");//密码登录


        User user = userService.queryByPhone(phone);

        if(user != null){
            if(user.getPassword().equals(password)){
                resp.getWriter().print(JSONObject.toJSONString(JsonData.buildSuccess(user.getId())));
            }

            else
                resp.getWriter().print(JSONObject.toJSONString(JsonData.buildError("对不起，密码错误！")));
        }
        else
            resp.getWriter().print(JSONObject.toJSONString(JsonData.buildError("对不起，用户不存在！")));


    }

    /**
     * 用户手机号注册
     */
    private void register() throws IOException {
        User user = JSONObject.parseObject(IOUtils.toString(req.getInputStream(), "utf-8"), User.class);

        int i = userService.insert(user);

        User new_user = userService.queryByPhone(user.getPhone());

        if(i > 0){

            ResponseJSONUtil.responseJSON(JsonData.buildSuccess(new_user.getId()),resp);
        }

    }

    private void updateUser() throws IOException {

        String s = IOUtils.toString(req.getInputStream(), "utf-8");

        JSONObject jsonObject = JSONObject.parseObject(s);

        //获取数据
        String imgUrl = jsonObject.getString("avatar");
        String id = jsonObject.getString("id");
        String name = jsonObject.getString("name");

        String school = jsonObject.getString("school");
        String number = jsonObject.getString("number");
        String phone = jsonObject.getString("phone");




        //更新
        User user = new User();
        user.setAvatar(imgUrl);
        user.setId(id);
        user.setName(name);

        user.setSchool(school);
        user.setNumber(number);
        user.setPhone(phone);


        UserService userService = BeanFactories.getBean(UserService.class);

        int i = userService.update(user);
        if(i>0){
            ResponseJSONUtil.responseJSON(JsonData.buildSuccess(i),resp);
        }else{
            ResponseJSONUtil.responseJSON(JsonData.buildError("修改失败"),resp);
        }


    }

    private void queryById() throws IOException {
        String userId = req.getParameter("userId");

        JsonData jsonData = JsonData.buildSuccess(userService.queryById(userId));
        ResponseJSONUtil.responseJSON(jsonData,resp);

    }

}
